package controller;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;

import util.CommonCalls;
import util.HibernateUtil;
import util.QueryBuilder;

import com.opensymphony.xwork2.ActionSupport;

public class DetailedSearchController extends ActionSupport implements ServletRequestAware{
	private static final long serialVersionUID = 1L;
	HttpServletRequest request;
	public void setServletRequest(HttpServletRequest arg0) {
		request = arg0;
	}
	
	public List<model.ProfileFieldDefinition> FieldDefinitions = CommonCalls.getFieldDefinitions();
	public List<model.BounBookUser> UserList;
	public List<Integer> SearchListDetails;
	public Hashtable<Integer,String> DefinedSearchParamaters;
	public String UserType = "'' or 1=1";
	public model.BounBookUser UserSearch = new model.BounBookUser();
	
	public int pageStatus = 0;
	
	public String execute() throws Exception {
		this.UserList = new ArrayList<model.BounBookUser>();
		this.pageStatus =0;
		return SUCCESS;
	}
	public String search() throws Exception{
		this.pageStatus = 1;
		this.GetSearchParameters();
		this.doSearch();
		return SUCCESS;
	}
	private void GetSearchParameters(){
		this.DefinedSearchParamaters = new Hashtable<Integer,String>();
		this.SearchListDetails = new ArrayList<Integer>();
		for(int a=0;a<this.FieldDefinitions.size();a++){
			if(request.getParameter(String.valueOf(this.FieldDefinitions.get(a).getId())) != null){
				this.DefinedSearchParamaters.put(this.FieldDefinitions.get(a).getId(), request.getParameter(String.valueOf(this.FieldDefinitions.get(a).getId())));
				this.SearchListDetails.add(this.FieldDefinitions.get(a).getId());
			}
		}
	}
	private void doSearch(){
		String subquery3 = "("+  QueryBuilder.Build(UserSearch.getName(), "%", "and", "bbu", "name","or 1=1") 
		 + "and" +	QueryBuilder.Build(UserSearch.getLastname(), "%", "and", "bbu", "lastname","or 1=1") 
		 + "and" +	QueryBuilder.Build(UserSearch.getEmail(), "%", "and", "bbu", "email","or 1=1")
		 + ") and (bbu.userType = "+this.UserType+") ";
		String topquery="from BounBookUser as bbu where "+subquery3+" and bbu.id IN (";
		String query = "select userId from UserProfile as up where ";
		for(int a=0;a<this.SearchListDetails.size();a++){
			if(a>0)
				query += "and";
			query += QueryBuilder.Build(this.DefinedSearchParamaters.get(this.SearchListDetails.get(a)), "%", "and", "up", "inputValue", " or 1=1");
		}
		topquery += query + "and up.isPrivate = '0') order by bbu.userType, bbu.name, bbu.lastname ";
		this.UserList = HibernateUtil.list(topquery);
		if(this.UserList.size() == 0)
			this.pageStatus = 2;
	}		
}
